package jp.eisbahn.mgapi.api.people;

import jp.eisbahn.mgapi.api.PagingResponse;
import jp.eisbahn.mgapi.http.HttpResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class PeopleResponse extends PagingResponse {
    
    @Override
    public void parseResponse(HttpResponse httpResponse) {
        String responseBody = httpResponse.getResponseBody();
        Object parsed = JSONValue.parse(responseBody);
        if (parsed instanceof JSONObject) {
            JSONObject obj = (JSONObject)parsed;
            Object entriesObj = obj.get("entry");
            if (entriesObj instanceof JSONArray) {
                JSONArray entries = (JSONArray)entriesObj;
                for (Object entryObj : entries) {
                    JSONObject entry = (JSONObject)entryObj;
                    addEntry(new Person(entry));
                }
            } else if (entriesObj instanceof JSONObject) {
                addEntry(new Person((JSONObject)entriesObj));
            }
            setStartIndex((Long)obj.get("startIndex"));
            setTotalResults((Long)obj.get("totalResults"));
            setItemsPerPage((Long)obj.get("itemsPerPage"));
        } else {
            throw new IllegalStateException("Response is not JSON object. " + responseBody);
        }
    }

}
